package com.zhouyangyang.shangcheng.file.client;

import com.zhouyangyang.file.pojo.FastDFSFile;
import lombok.extern.slf4j.Slf4j;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.core.io.ClassPathResource;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @PackageName: com.zhouyangyang.shangcheng.file.client
 * @ClassName: FastDFSClient
 * @Author: zhouyangyang
 * @Date: 2020/7/26 14:54
 * @Description:
 */
@Slf4j
public class FastDFSClient {
    /**
     * 初始化加载FastDFS的TrackerServer配置
     */
    static {
        try {
            String path = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
            ClientGlobal.init(path);
        } catch (Exception e) {
            log.error("FastDFS Client Init Fail!{}", e.getMessage());
        }
    }

    /**
     * 文件上传
     */
    public static String[] upload(FastDFSFile file) {
        //获取文件的作者
        NameValuePair[] meta = new NameValuePair[1];
        meta[0] = new NameValuePair("author", file.getAuthor());
        //接收返回数据
        String[] uploadResults = null;
        StorageClient storageClient = null;
        //创建StorageClient客户端对象
        try {
            storageClient = getTrackerClient();
            /***
             * 文件上传
             * 1)文件字节数组
             * 2)文件扩展名
             * 3)文件作者
             */
            uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta);
        } catch (Exception e) {
            log.error("Exception when uploadind the file:{}" + file.getName(), e.getMessage());
        }
        if (uploadResults == null && storageClient != null) {
            log.error("upload file fail, error code:{}", storageClient.getErrorCode());
        }
        //获取组名
        String groupName = uploadResults[0];
        //获取文件存储路径
        String path = uploadResults[1];
        return uploadResults;
    }

    /**
     * 获取文件信息
     *
     * @param groupName      组名
     * @param remoteFileName 文件完整存储名
     * @return
     */
    public static FileInfo getFile(String groupName, String remoteFileName) {
        try {
            StorageClient storageClient = getTrackerClient();
            return storageClient.get_file_info(groupName, remoteFileName);
        } catch (Exception e) {
            log.error("Exception: Get File from Fast DFS failed {}", e.getMessage());
            return null;
        }
    }

    /**
     * 文件下载
     *
     * @param groupName      组名
     * @param remoteFileName 文件路径完整名
     * @return
     */
    public static InputStream downFile(String groupName, String remoteFileName) {
        InputStream ins = null;
        try {
            //创建StorageClient
            StorageClient storageClient = getTrackerClient();
            byte[] bytes = storageClient.download_file(groupName, remoteFileName);
            ins = new ByteArrayInputStream(bytes);
        } catch (Exception e) {
            log.error("Exception: Get File from Fast DFS failed {}", e.getMessage());
        }
        return ins;
        //下载文件
    }

    /**
     * 删除文件
     *
     * @param groupName      组名
     * @param remoteFileName 文件路径完整名
     */
    public static void deleteFile(String groupName, String remoteFileName) {
        try {
            StorageClient storageClient = getTrackerClient();
            storageClient.delete_file(groupName, remoteFileName);
        } catch (Exception e) {
            log.error("Exception: Delete File from Fast DFS failed {}", e.getMessage());
        }
    }

    /**
     * 获取storage 组
     */
    public static StorageServer[] getStorageServers(String groupName) throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        return trackerClient.getStoreStorages(trackerServer, groupName);
    }

    /***
     * 获取Storage信息,IP和端口
     * @param groupName
     * @param remoteFileName
     * @return
     * @throws IOException
     */
    public static ServerInfo[] getFetchStorages(String groupName, String remoteFileName) throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
    }

    /***
     * 获取Tracker服务地址
     * @return
     * @throws IOException
     */
    public static String getTrackerUrl() throws IOException {
        return "http://" + getTrackerServer().getInetSocketAddress().getHostString() + ":" +
                ClientGlobal.getG_tracker_http_port() + "/";
    }

    /**
     * 获取storage客户端
     *
     * @return
     */
    private static StorageClient getTrackerClient() throws IOException {
        TrackerServer trackerServer = getTrackerServer();
        StorageClient storageClient = new StorageClient(trackerServer, null);
        return storageClient;
    }

    /**
     * 获取tracker
     *
     * @return
     */
    private static TrackerServer getTrackerServer() throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        return trackerServer;
    }
}
